//index.js
//获取应用实例
const app = getApp()
var api = require('../../utils/api.js')
var util = require('../../utils/util.js');

Page({
  data: {                                                    
    indicatorDots: false,
    autoplay: false,
    interval: 5000,
    duration: 500,
    circular: true,
    lastTime: 0,
    nextMargin: "100px",
    product: [],
    page: 1,
    limit: 20,
    total_page: 0,
  },

  onLoad: function (options) {
    this.setData({
      windowHeight: app.globalData.windowHeight,
    })
    if (options.q) {
      var link = options.q;
      link = unescape(decodeURI(link));
      var num = link.indexOf("?");
      link = link.substring(num + 1);
      var ary = link.split("&");
      var obj = {}
      for (var i = 0; i < ary.length; i++) {
        var key = ary[i].split("=")[0];
        var value = ary[i].split("=")[1];
        obj[key] = value
      }
      var shopId = obj.shopId;
      if (shopId){
        app.globalData.shopId = shopId
      }
      this.setData(obj)
      
    }
  },
  onShow: function (options) {
    var that = this;

    //判断进入场景
    if (app.globalData.sceneId != '1011' & app.globalData.sceneId != '1013'){
      app.globalData.shopId = null
    }


    this.setData({
      lastTime: 0
    })
    if (this.data.page > 1) {
      return;
    }
    if (app.globalData.accountInfo.uid) {
      that.bannerList();
      that.getProductLIst();
      that.getTopGoods();
      that.getCategoryList();
      that.setData({
        setLogin: "login"
      })
    } else {
      wx.getSetting({
        success: function(res) {
          if (res.authSetting['scope.userInfo']) {
            that.authorization();
          } else {
            that.setData({
              setLogin: "noLogin"
            })
          }
        }
      })
    }
  },

  bannerList: function() {
    var params = new Object();
    params.type = 2;
    var that = this;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'user/banner',
      success: function(res) {
        wx.hideLoading()
        if (util.isEmpty(res.data.code)) {
          if (res.data.data.lenght > 1) {
            var indicatorDots = true
          } else {
            var indicatorDots = false
          }
          that.setData({
            bannerList: res.data.data,
            indicatorDots: indicatorDots
          })
        }
      },
      fail: function(fail) {
        wx.hideLoading()
        util.showError("登录失败，请检查网络");

      }
    })
  },


  sweepCode: function() {
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        var scanCode = res.result;
        var shopId = scanCode.substring(scanCode.lastIndexOf("=") + 1);
        shopId = shopId/1;
        // console.log(shopId);
        // return
        var regPos = / ^\d+$/; // 非负整数
        if (!isNaN(shopId) ){
          wx.navigateTo({
            url: '/index/pages/goodsList/goodsList?index=2&shopId=' + shopId,
          })
        }else{
          util.showError("二维码错误");
        }
      },
      fail: function(e) {
        if (e.errMsg != 'scanCode:fail cancel') {
          util.showError("扫码失败");
        }
      }
    });
  },

  // 登录
  authorization: function() {
    var that = this
    wx.login({
      success: function(res_login) {
        wx.getUserInfo({
          withCredentials: true,
          success: function(res_user) {
            // console.log(res_login);
            var login_code = res_login.code;
            var login_encryptedData = res_user.encryptedData;
            var login_iv = res_user.iv;
            that.autoLogin(login_code, login_encryptedData, login_iv);
            that.setData({
              setLogin: 'login',
              avatarUrl: res_user.userInfo.avatarUrl,
              nickName: res_user.userInfo.nickName,
            });
          },
          fail: function(fail_res) {
            if (fail_res.errMsg == "getUserInfo:fail auth deny") {
              // that.showModal();
            } else {
              util.showError("登录失败");
            }
          }
        })
      },
      fail: function(fail_login) {
        //console.log("fail");
      }
    })
  },

  autoLogin: function(login_code, login_encryptedData, login_iv) {
    var that = this
    var params = {
      code: login_code,
      encryptedData: login_encryptedData,
      iv: login_iv
    }
    api.POST({
      params: params,
      url: app.globalData.login_url,
      success: function(res) {
        if (util.isEmpty(res.data.code)) {
          app.globalData.accountInfo = res.data.data.result;
          wx.setStorageSync('accountInfo', res.data.data.result)
          that.bannerList();
          that.getProductLIst();
          that.getTopGoods();
          that.getCategoryList();
        }
      },
      fail: function(fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },

  // 重新授权
  reAuthorization: function() {
    var that = this
    wx.openSetting({
      success: function(res) {
        if (res.authSetting["scope.userInfo"]) {
          //检测是否有登录信息
          if (that.data.nickName == "" && that.data.avatarUrl == "") {
            that.authorization();
          }
        } else {
          that.showModal();
        }
      }
    })
  },

  showModal: function() {
    var that = this;
    wx.showModal({
      title: '警告',
      content: '若不授权，则无法使用',
      confirmText: '授权',
      cancelText: '不授权',
      success: function(suress) {
        if (suress.confirm) {
          that.reAuthorization();
        } else {
          that.showModal();
        }
      }
    })
  },
  // 获取商品列表
  getProductLIst: function() {
    var that = this;
    var page = this.data.page;
    var params = {
      limit: that.data.limit,
      type:1,
      page: that.data.page
    }
    api.POST({
      params: params,
      url: app.globalData.base_url + 'goods/getList',
      success: function(res) {
        wx.hideLoading();
        if (util.isEmpty(res.data.code)) {
          var paging = res.data.data.search;
          var totalPage = paging.total_page;
          var resultList = res.data.data.goods_list;

          if (page == 1) {
            var itemData = resultList;
          } else {
            var itemData = that.data.product.concat(resultList)
          }

          that.setData({
            total_page: totalPage,
            product: itemData
          })

        } else {
          util.showError(res.data.message);
        }
      },
      fail: function(fail) {
        util.showError("登录失败，请检查网络");

      }
    })
  },
  //查看商品详情
  productDetails: function(e) {
    var sku_code = e.currentTarget.dataset.sku_code;
    var curTime = e.timeStamp;
    var lastTime = this.data.lastTime;
    this.setData({
      lastTime: curTime
    })
    if (lastTime > 0) {
      if (curTime - lastTime < 500) {
        return false;
      }
    }
    wx.navigateTo({
      url: '/index/pages/productDetails/productDetails?sku_code=' + sku_code
    })
  },
  //加载更多
  loadMore: function() {
    if (this.data.page >= this.data.total_page) {
      return;
    }
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      page: this.data.page + 1
    });
    this.getProductLIst();
  },

  //刷新页面
  resetData: function() {
    var that = this
    that.setData({
      page: 1,
      hasMore: true
    });
  },
  //页面下拉刷新
  onPullDownRefresh: function() {
    var that = this;

    setTimeout(function() {
      that.resetData()
    }, 1000)
  },

  //页面上拉触底
  onReachBottom: function(e) {
    this.loadMore();
  },
  shopList: function(e) {
    var curTime = e.timeStamp;
    var lastTime = this.data.lastTime;
    this.setData({
      lastTime: curTime
    })
    if (lastTime > 0) {
      if (curTime - lastTime < 500) {
        return false;
      }
    }
    wx.navigateTo({
      url: '/index/pages/shopList/shopList'
    })
  },
  // 获取置顶商品
  getTopGoods: function() {
    var that = this;
    api.POST({
      params: "",
      url: app.globalData.base_url + 'goods/getTop',
      success: function(res) {
        if (util.isEmpty(res.data.code)) {
          that.setData({
            topGoodsLeft:res.data.data[0],
            topGoodsRightFirst: res.data.data[1],
            topGoodsSecond: res.data.data[2],
            topGoodsList: res.data.data.slice(3)
          })
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function(fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },
  // 获取首页分类
  getCategoryList: function () {
    var that = this;
    api.POST({
      params: "",
      url: app.globalData.base_url + 'goods/categoryList',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          that.setData({
            categoryList: res.data.data
          })
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },
  hops:function(){
    wx.navigateTo({
      url: '/play/pages/hops/hops'
    })
  },
  cart:function(){
    wx.navigateTo({
      url: '/index/pages/cart/cart'
    })
  },
  navLink:function(e){
    var sku_code = e.currentTarget.dataset.sku_code;
    var id = e.currentTarget.dataset.id;
    var img = e.currentTarget.dataset.image;
    if (sku_code){
      wx.navigateTo({
        url: '/index/pages/productDetails/productDetails?sku_code=' + sku_code
      })
    }else{
      wx.navigateTo({
        url: '/index/pages/productClass/productClass?id=' + id + "&img=" + img
      })
    }
  },
  footprint: function () {
    wx.navigateTo({
      url: '/index/pages/storeFootprint/storeFootprint'
    })
  },
  onShareAppMessage:function(){
    
  }

})